package cn.qidd.keep.common.service.file.impl;

import cn.qidd.keep.common.model.UploadFile;
import cn.qidd.keep.common.service.file.FileService;
import cn.qidd.keep.domain.web.UserVO;
import com.mongodb.BasicDBObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by sunyanping on 2018/10/11
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Override
    public UploadFile upload(UserVO userVO, MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        BasicDBObject metadata = new BasicDBObject();
        metadata.put("userId", userVO.getId());
        metadata.put("userName", userVO.getUserName());
        metadata.put("realName", userVO.getRealName());
        metadata.put("timestamp", System.currentTimeMillis());
        String fileId = gridFsTemplate.store(inputStream, file.getOriginalFilename(), metadata).toHexString();
        return backUploadFile(file, fileId);
    }

    private UploadFile backUploadFile(MultipartFile file, String fileId) {
        String originalFilename = StringUtils.isBlank(file.getOriginalFilename()) ? "" : file.getOriginalFilename();
        UploadFile uploadFile = new UploadFile();
        uploadFile.setId(fileId);
        uploadFile.setFilename(originalFilename);
        int lastIndexOf = originalFilename.lastIndexOf(".");
        uploadFile.setFileSuffix(lastIndexOf < 0 ? "" : originalFilename.substring(lastIndexOf-1));
        return uploadFile;
    }


}
